<template>
  <!-- 订单确认收货地址 -->
  <van-address-list
    v-if="action"
    v-model="active"
    :list="list"
    default-tag-text="默认"
    @add="addressAdd"
    @edit="addressEdit"
    @select="AddressChange"
  />
  <!-- 从会员中心进入收货地址 -->
  <van-address-list
    v-else
    v-model="active"
    :list="list"
    default-tag-text="默认"
    @add="addressAdd"
    @edit="addressEdit"
    @select="AddressSelect"
  />
</template>
<script setup>
import { onBeforeMount, reactive } from "vue";
const { proxy } = getCurrentInstance();
//接收关键词参数
let action = ref(proxy.$route.query.action ? proxy.$route.query.action : '')

const business = proxy.$business.value;
//标识,是否为默认地址
const active = ref(0);
// 收货地址列表
const list = reactive([]);

onBeforeMount(async () => {
  AddressList();
});

//获取收货地址列表
const AddressList = async () => {
  var result = await proxy.$POST({
    url: "address/index",
    params: { busid: business.id },
  });

  //要么是出错 要么没有数据
  if (result.code == 0) {
    proxy.$fail(result.msg);
    return false;
  }

  result.data.map((item) => {
    if (item.status == "1") active.value = item.id;

    //重组收货地址结构
    list.push({
      id: item.id,
      name: item.consignee,
      tel: item.mobile,
      address: `${item.region_text} ${item.address}`,
      isDefault: item.status == "1" ? true : false,
    });
  });
};

//添加收货地址
const addressAdd = () => {
  proxy.$router.push("/address/add");
};

//编辑地址
const addressEdit = (item) =>
  proxy.$router.push({ path: "/address/edit", query: { id: item.id } });

//切换默认的收获地址
const AddressSelect = async (item, index) => {
  var result = await proxy.$POST({
    url: "/address/check",
    params: {
      busid: proxy.$business.value.id,
      id: item.id,
    },
  });

  if (result.code == 0) {
    proxy.$fail(result.msg);
    return false;
  }

  //成功就修改默认的状态
  list.map((value) => {
    //把所有的地址全部修改为非默认地址
    value.isDefault = false;

    //刚刚切换的地址 设置为默认的
    if (value.id == item.id) value.isDefault = true;
  });
  console.log(index)
};

//切换收货地址
const AddressChange = (item, index)=>{
  item.region_text = item.address
  proxy.$cookies.set('address',item)
  proxy.$router.go(-1)
}
</script>